package com.yoke.controller.rewrite;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yoke.common.JsonMessage;
import com.yoke.common.base.RewriteBaseControl;
import com.yoke.common.tools.UrlPath;
import com.yoke.controller.copy.CopyIndexControl;
import com.yoke.service.rewrite.ConfService;
import com.yoke.service.rewrite.EditRewriteServer;
import com.yoke.system.log.LogType;
import com.yoke.system.log.SystemLog;
import com.yoke.util.EncryptUtil;
import com.yoke.util.FileUtil;
import com.yoke.util.StringUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by jiangzeyin on 2017/8/2.
 */
@Controller
@RequestMapping("rewrite")
public class RewriteIndexControl extends RewriteBaseControl {
    @Resource
    ConfService confService;
    @Resource
    EditRewriteServer editRewriteServer;

    /**
     * 扫描所有可以跳转的
     *
     * @param name
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "index.html", produces = MediaType.TEXT_HTML_VALUE)
    public String index(String name) throws IOException {
        JSONObject allUrl = CopyIndexControl.getInfo(UrlPath.Type.None, name, getConfPath());
        JSONObject rewriteUrl = CopyIndexControl.getInfo(UrlPath.Type.Rewrite, name, getConfPath());
        if (allUrl != null && rewriteUrl != null) {
            Set<Map.Entry<String, Object>> stringObjectSet = allUrl.entrySet();
            stringObjectSet.forEach(stringObjectEntry -> {
                String key = stringObjectEntry.getKey();
                JSONArray rewriteUrlJSONArray = rewriteUrl.getJSONArray(key);
                if (rewriteUrlJSONArray == null) {
                    return;
                }
                JSONArray urlArray = (JSONArray) stringObjectEntry.getValue();
                if (urlArray == null) {
                    return;
                }
                urlArray.forEach(o -> {
                    JSONObject jsonObject = (JSONObject) o;
                    String url = jsonObject.getString("url");
                    Iterator<Object> iterable = rewriteUrlJSONArray.iterator();
                    while (iterable.hasNext()) {
                        JSONObject jsonObject1 = (JSONObject) iterable.next();
                        String url1 = jsonObject1.getString("url");
                        if (url.startsWith(url1)) {
                            jsonObject.put("ing", true);
                            jsonObject.put("toUrl", jsonObject1.getString("toUrl"));
                            iterable.remove();
                        } else {
                            jsonObject1.put("ing", true);
                        }
                    }
                });
                // 没有处理完的
                if (!rewriteUrlJSONArray.isEmpty()) {
                    urlArray.addAll(rewriteUrlJSONArray);
                }
                // 移除已经处理了的
                rewriteUrl.remove(key);
            });
            // 最后没有扫描到的
            if (!rewriteUrl.isEmpty()) {
                rewriteUrl.forEach((k, v) -> {
                    JSONArray jsonArray = (JSONArray) v;
                    jsonArray.forEach(o -> {
                        JSONObject jsonObject = (JSONObject) o;
                        jsonObject.put("ing", true);
                    });
                });
                allUrl.putAll(rewriteUrl);
            }
        }
        request.setAttribute("data", allUrl);
        return "rewrite/index";
    }

    /**
     * 取消跳转
     *
     * @param url
     * @param tag
     * @return
     */
    @RequestMapping(value = "cancel_rewrite.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String cancel_rewrite(String url, String tag) {
        String[] strings = check(url, tag);
        if (strings[0] != null)
            return strings[0];
        String path = strings[2];
        String tag_ = strings[1];
        boolean urlAll = true;
        try {
            List<String[]> logs = confService.getRewritesLog(path);
            if (logs != null)
                for (String[] item : logs) {
                    if (tag_.equals(item[0])) {
                        urlAll = Boolean.valueOf(item[3]);
                        break;
                    }
                }
        } catch (IOException e1) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("解析失败", e1);
            return JsonMessage.getString(100, "操作失败，请联系管理员,获取日志信息失败");
        }
        if ("/index.html".equals(tag_)) {
            urlAll = false;
        }
        StringBuffer stringBuffer = editRewriteServer.delRewrite(tag_, path, urlAll);
        if (stringBuffer == null)
            return JsonMessage.getString(100, "操作失败，请联系管理员");
        try {
            FileUtil.writeFile(path, stringBuffer);
        } catch (IOException e1) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("解析失败", e1);
            return JsonMessage.getString(100, "操作失败，请联系管理员");
        }
        reloadNginx("取消" + url + " 跳转");
        return JsonMessage.getString(200, "取消成功");
    }

    @RequestMapping(value = "add_rewrite.html", produces = MediaType.TEXT_HTML_VALUE)
    public String add_rewrite(String url, String tag) {
        String oldUrl = url;
        url = StringUtil.convertNULL(url);
        if (!url.contains("://")) {
            request.setAttribute("tip", "地址错误");
            return "rewrite/edit_rewrite";
        }
        url = url.substring(url.indexOf("://") + 3);
        int s = url.indexOf("/");
        int e = url.lastIndexOf("/");
        String tag_;
        if (s == e) {
            String temp = url.substring(s);
            if ("/index.html".equals(temp)) {
                tag_ = "/index.html";
            } else {
                request.setAttribute("tip", "地址不支持");
                return "rewrite/edit_rewrite";
            }
        } else {
            tag_ = url.substring(s, e + 1);
        }

        String path;
        try {
            path = EncryptUtil.decrypt(tag);
            File file = new File(path);
            if (!file.exists()) {
                request.setAttribute("tip", "不存在跳转配置");
                return "rewrite/edit_rewrite";
            }
        } catch (Exception e1) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("解析失败", e1);
            request.setAttribute("tip", "解析失败");
            return "rewrite/edit_rewrite";
        }
        request.setAttribute("url", oldUrl);
        String upLog = getUpLog(path, tag_);
        request.setAttribute("upLog", upLog);
        request.setAttribute("tag", tag);
        return "rewrite/edit_rewrite";
    }

    @RequestMapping(value = "save_rewrite.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String save_rewrite(String url, String tag, String toUrl) {
        String[] strings = check(url, tag);
        if (strings[0] != null)
            return strings[0];
        String path = strings[2];
        String tag_ = strings[1];
        try {
            boolean urlAll = true;
            if ("/index.html".equals(tag_)) {
                urlAll = false;
            }
            editRewriteServer.saveRewrite(tag_, path, tag_, url, toUrl, urlAll, true);
        } catch (IOException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("保存跳转失败", e);
            return JsonMessage.getString(100, "保存失败，请及时联系管理员");
        }
        reloadNginx("添加" + url + " 跳转到：" + toUrl);
        return JsonMessage.getString(200, "处理成功");
    }

    /**
     * 验证参数
     *
     * @param url
     * @param tag
     * @return
     */
    private String[] check(String url, String tag) {
        String[] strings = new String[3];
        url = StringUtil.convertNULL(url);
        if (!url.contains("://")) {
            strings[0] = JsonMessage.getString(140, "地址错误");
            return strings;
        }
        url = url.substring(url.indexOf("://") + 3);
        int s = url.indexOf("/");
        int e = url.lastIndexOf("/");
        if (s == e) {
            String temp = url.substring(s);
            if ("/index.html".equals(temp)) {
                strings[1] = "/index.html";
            } else {
                strings[0] = JsonMessage.getString(140, "地址不支持");
                return strings;
            }
        } else {
            strings[1] = url.substring(s, e + 1);// tag_;
        }
        //String tag_ =
        String path;
        try {
            path = EncryptUtil.decrypt(tag);
            File file = new File(path);
            if (!file.exists()) {
                strings[0] = JsonMessage.getString(404, "不存在跳转配置");
                return strings;
            }
        } catch (Exception e1) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("解析失败", e1);
            strings[0] = JsonMessage.getString(404, "跳转配置读取异常");
            return strings;
        }
        strings[0] = null;
        strings[2] = path;
        return strings;
    }

    /**
     * 获取上传跳转记录
     *
     * @param path
     * @param tag
     * @return
     */
    private String getUpLog(String path, String tag) {
        try {
            JSONObject jsonObject = confService.getRewrites(path, true, false);
            List<?> rewrite_logs = jsonObject.getObject("rewrite_logs", List.class);
            if (rewrite_logs == null || rewrite_logs.size() <= 0) {
                return doJson(jsonObject, tag);
            }
            for (Object object : rewrite_logs) {
                String[] item = (String[]) object;
                boolean find;
                if (tag.startsWith("http://")) {
                    find = item[1].equals(tag);
                } else {
                    find = item[0].equals(tag);
                }
                if (find) {
                    return item[2];
                }
            }
            return doJson(jsonObject, tag);
        } catch (IOException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("获取异常", e);
        }
        return null;
    }

    private String doJson(JSONObject jsonObject, String tag) {
        List<?> list = jsonObject.getObject("rewrites", List.class);
        if (list == null || list.size() <= 0) {
            return null;
        }
        for (Object object : list) {
            String[] item = (String[]) object;
            if (item[0].equals(tag)) {
                return item[1];
            }
        }
        return null;
    }
}
